package com.spring.nameparamjdbc;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.jdbc.core.namedparam.BeanPropertySqlParameterSource;
import org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate;
import org.springframework.jdbc.core.namedparam.SqlParameterSource;
import org.springframework.jdbc.core.namedparam.SqlParameterSourceUtils;

public class Main {

	private NamedParameterJdbcTemplate namedParameterJdbcTemplate;

	public static void main(String[] args) {
		ClassPathXmlApplicationContext ctx = new ClassPathXmlApplicationContext("nameparamjdbc.xml");
		NamedParameterJdbcTemplate p = (NamedParameterJdbcTemplate) ctx.getBean("namedParameterJdbcTemplate");
		query(p);
	//	batchInsert(p);
	}

	public static void query(NamedParameterJdbcTemplate p) {
		String sql = "select * from role";
		RowMapper<Role> rowMapper = new BeanPropertyRowMapper<Role>(Role.class);
		List<Role> list = p.query(sql, rowMapper);
		for (Role role : list) {
			System.out.println(role.getRoleName());
		}
	}

	public static void insert1(NamedParameterJdbcTemplate p) {
		String sql = "insert into  role(id,role_name) values (:id,:roleName)";
		List<Object[]> list = new ArrayList<Object[]>();
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("id", 6);
		map.put("roleName", "liquan66");
		p.update(sql, map);
	}
	public static void insert2(NamedParameterJdbcTemplate p) {
		String sql = "insert into  role(id,role_name) values (:id,:roleName)";
		List<Object[]> list = new ArrayList<Object[]>();
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("id", 6);
		map.put("roleName", "liquan66");
		Role role = new Role();
		role.setId(9);
		role.setRoleName("role9");
		SqlParameterSource paramSource=new BeanPropertySqlParameterSource(role);
		p.update(sql, paramSource);
	}
	
	/**
	 * 批量插入实体
	 * @param p
	 */
	public static void batchInsert(NamedParameterJdbcTemplate p) {
		String sql = "insert into  role(role_name) values (:roleName)";
		List<Object[]> list = new ArrayList<Object[]>();
	 
		Role role = new Role();
		role.setRoleName("role10");
		
		
		Role role2 = new Role();
		role2.setRoleName("role10");
		
		Role[] roles = {role,role2};
		
		SqlParameterSource[] paramSources= SqlParameterSourceUtils.createBatch(roles);;
		p.batchUpdate(sql,   paramSources);
	}
}
